package com.kingwood.algorithm.test200;

import java.util.*;

/**
 * @Author 22025812
 * @Description: TODO
 * @Date: 2024/3/29 17:05
 * @Modified By：
 * @Version 1.0
 */
public class IPFind {
    static class IPInfo {
        String cityName;
        long startIp;
        long endIp;

        public IPInfo(String cityName, String startIp, String endIp) {
            this.cityName = cityName;
            this.startIp = ipToInteger(startIp);
            this.endIp = ipToInteger(endIp);
        }
    }

    // IP地址转整型
    public static long ipToInteger(String ipAddress) {
        String[] parts = ipAddress.split("\\.");
        long result = 0;
        for (int i = 0; i < 4; i++) {
            // 将每一段IP地址转换为十进制并乘以相应权重
            int part = Integer.parseInt(parts[i]);
            result += (part << (8 * (3 - i)));
        }

        return result;
    }

    public static String findCity(String[] findIpArr, List<IPInfo> ipInfoList) {
        StringJoiner sj = new StringJoiner(",");

        HashMap<String, IPInfo> ipInfoMap = new HashMap<>();

        // 遍历待查询的IP地址
        for (String ip : findIpArr) {
            long ipDec = ipToInteger(ip);
            // 将带查询IP与城市IP段列表逐一匹配
            for (IPInfo ipInfo : ipInfoList) {
                // 如果带查询的IP地址 在某城市的IP段范围内，且该城市的IP段长度更小，则该城市为待查询IP的最佳匹配城市
                if (ipDec >= ipInfo.startIp && ipDec <= ipInfo.endIp) {
                    if (ipInfoMap.containsKey(ip)) {
                        IPInfo preInfo = ipInfoMap.get(ip);
                        if ((preInfo.endIp - preInfo.startIp) > (ipInfo.endIp - ipInfo.startIp)) {
                            ipInfoMap.put(ip, ipInfo);
                        }
                    } else {
                        ipInfoMap.put(ip, ipInfo);
                    }
                }
            }
        }

        for (String ip : findIpArr) {
            if (ipInfoMap.containsKey(ip)) {
                sj.add(ipInfoMap.get(ip).cityName);
            }
        }

        return sj.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String ipStr = scanner.nextLine();
        String[] ipkeys = ipStr.split(";");
        List<IPInfo> ipInfoList = new ArrayList<>();

        for (int i = 0; i < ipkeys.length; i++) {
            String ipInfoStr = ipkeys[i];
            String[] ipInfo = ipInfoStr.split("=");
            int idx = ipInfo[1].indexOf(",");
            String startIp = ipInfo[1].substring(0, idx);
            String endIp = ipInfo[1].substring(idx + 1);
            IPInfo info = new IPInfo(ipInfo[0], startIp, endIp);
            ipInfoList.add(info);
        }

        String findIpStr = scanner.nextLine();
        String[] findIpArr = findIpStr.split(",");
        System.out.println(findCity(findIpArr, ipInfoList));
    }
}
